package com.faintlight.controller;

import com.faintlight.dto.ChainDTO;
import com.faintlight.service.ChainService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chains")
@Tag(name = "善意传递", description = "善意传递链管理接口")
@RequiredArgsConstructor
public class ChainController {

    private static final Logger logger = LoggerFactory.getLogger(ChainController.class);
    private final ChainService chainService;

    @PostMapping("/start/{capsuleId}")
    @Operation(summary = "启动善意传递链")
    public ResponseEntity<ChainDTO> startChain(@PathVariable @Min(1) Long capsuleId, @RequestHeader("X-User-Id") Long userId) {
        ChainDTO chain = chainService.startChain(capsuleId, userId);
        return ResponseEntity.ok(chain);
    }

    @PostMapping("/{chainId}/nodes")
    @Operation(summary = "向传递链添加节点")
    public ResponseEntity<ChainDTO> addNode(
            @PathVariable @Min(1) Long chainId,
            @RequestParam String message,
            @RequestHeader("X-User-Id") Long userId) {
        ChainDTO chain = chainService.addNodeToChain(chainId, userId, message);
        return ResponseEntity.ok(chain);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取传递链详情")
    public ResponseEntity<ChainDTO> getChain(@PathVariable @Min(1) Long id) {
        ChainDTO chain = chainService.getChainById(id);
        return ResponseEntity.ok(chain);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户参与的善意传递链")
    public ResponseEntity<List<ChainDTO>> getUserChains(@PathVariable Long userId) {
        List<ChainDTO> chains = chainService.getChainsByParticipant(userId);
        return ResponseEntity.ok(chains);
    }

    @GetMapping
    @Operation(summary = "获取所有传递链（测试用）")
    public ResponseEntity<List<ChainDTO>> getAllChains() {
        List<ChainDTO> chains = chainService.getAllChains();
        return ResponseEntity.ok(chains);
    }
    @GetMapping("/user/{userId}/count")
    @Operation(summary = "获取用户参与的传递链数量")
    public ResponseEntity<Long> getUserChainCount(@PathVariable Long userId) {
        Long count = chainService.getUserChainCount(userId);
        return ResponseEntity.ok(count);
    }
}
